package com.ruoyi.web.controller.customer;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ReceivedMessage;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BulkSendName;
import com.ruoyi.web.controller.webSocket.WebSocketServer;
import com.ruoyi.system.domain.CustomerInfo;
import com.ruoyi.system.domain.CustomerChat;
import com.ruoyi.system.domain.WaUser;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.StatusCheckService;
import com.ruoyi.system.service.impl.WaURLService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 坐席信息
 */
@RestController
@RequestMapping("/customer/user")
public class CusUserController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CusUserController.class);

    @Autowired
    private StatusCheckService statusCheckService;

    @Autowired
    private ICusUserService cusUserService;

    @Autowired
    private ICustomerChatService customerChatService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private Environment env;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WaURLService waURLService;

    @Autowired
    private WebSocketServer webSocketServer;




    /**
     * 获取坐席列表
     */
    @PreAuthorize("@ss.hasPermi('customer:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustomerInfo user) {
        startPage();
        List<CustomerInfo> list = cusUserService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取坐席列表
     */
    @PreAuthorize("@ss.hasPermi('chat:ui:list')")
    @GetMapping("/wa/list")
    public TableDataInfo waList(String userName) {
        startPage(100);
//        CusUser user = new CusUser();
//        String name = getUsername();
        CustomerInfo user = new CustomerInfo();
        List<CustomerInfo> userlist = cusUserService.selectUserList(user);
//        List<WaUser> list = cusUserService.selectCustomerChatList(userName, userlist);
        return null;
    }


//    @PreAuthorize("@ss.hasPermi('client:user:edit')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getCustomerById(@PathVariable String id) {
//        return success(cusUserService.selectChatById(id));
//    }    85253681211
//            85253678207


    /**
     * 客户端准备好了
     *
     * @param contactNumber
     * @return
     */
    @PreAuthorize("@ss.hasPermi('customer:user:query')")
    @GetMapping("/ready/{contactNumber}")
    public AjaxResult clientReady(@PathVariable String contactNumber) {
        CustomerInfo cusUser = cusUserService.selectUserByNumber(contactNumber);
        cusUser.setLinkStatus("0");
        return success(cusUserService.updateUser(cusUser));
    }

    /**
     * 新增坐席
     */
    @PreAuthorize("@ss.hasPermi('customer:user:add')")
    @Log(title = "坐席管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CustomerInfo user) {
        if (!cusUserService.checkContactNumberUnique(user)) {
            return error("新增坐席'" + user.getContactNumber() + "'失败，whatsapp账号已存在");
        } else if (StringUtils.isEmpty(user.getUserName())) {
            return error("新增坐席所属用户账户为空");
        }
        SysUser u = sysUserService.selectUserByUserName(user.getUserName());
        if (StringUtils.isNull(u)) {
            return error("新增坐席所属用户账户不存在");
        }
        user.setUserId(u.getUserId());
        user.setDeptId(u.getDeptId());
        return toAjax(cusUserService.insertUser(user));
    }

    /**
     * 修改坐席
     */
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CustomerInfo user) {
        if (StringUtils.isEmpty(user.getUserName())) {
            return error("新增坐席所属用户账户为空");
        }
        SysUser u = sysUserService.selectUserByUserName(user.getUserName());
        if (StringUtils.isNull(u)) {
            return error("新增坐席所属用户账户不存在");
        }
        user.setUserId(u.getUserId());
        user.setDeptId(u.getDeptId());
        return toAjax(cusUserService.updateUser(user));
    }

    /**
     * 删除坐席
     */
    @PreAuthorize("@ss.hasPermi('customer:user:remove')")
    @Log(title = "坐席管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String[] id) {
        return toAjax(cusUserService.deleteUserByNumbers(id));
    }

    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @GetMapping(value = "/{id}")
    public AjaxResult getCustomer(@PathVariable String id) {
        return success(cusUserService.selectChatById(id));
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('customer:user:changeStatus')")
    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @Anonymous
    public AjaxResult changeStatus(@RequestBody CustomerInfo user) {
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if (sysUser.getUserName().equals("A001")) {
            user.setTemplateId("103");
        }
        return toAjax(cusUserService.updateChatStatus(user));
    }


    @Log(title = "坐席管理", businessType = BusinessType.UPDATE)
    @PutMapping("/linkStatus")
//    @Anonymous
    public AjaxResult linkStatus(@RequestBody CustomerInfo user) {
//        LoginUser loginUser = getLoginUser();
//        SysUser sysUser = loginUser.getUser();
//        if (sysUser.getUserName().equals("A001")) {
//            user.setTemplateId("103");
//        }
        return toAjax(cusUserService.updateLinkStatus(user));
    }

    /**
     * 获取登录二维码
     */
    @PreAuthorize("@ss.hasPermi('customer:user:link')")
    @GetMapping("/createClient/{contactNumber}")
    public AjaxResult createClient(@PathVariable("contactNumber") String contactNumber) {

        String url = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.createClient");
        String rspStr = HttpUtils.sendGet(url + contactNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        log.info("createClient:" + rspStr);
        statusCheckService.startManualCheck(contactNumber);
        return ajax;
    }

    /**
     * 断开链接
     *
     * @param contactNumber
     * @return
     */
    @GetMapping("/disconnectedClient/{contactNumber}")
    public AjaxResult disconnectedClient(@PathVariable("contactNumber") String contactNumber) {
        CustomerInfo user = new CustomerInfo();
        user.setContactNumber(contactNumber);
        user.setLinkStatus("1");
        cusUserService.updateLinkStatus(user);
        statusCheckService.cancelTask(contactNumber);
        log.info("----------------  deleteClient  deleteClient-------------------");

        String url = waURLService.getContactNumberURL(contactNumber, "apiSevicePath.deleteClient");

        String rspStr = HttpUtils.sendGet(url + contactNumber);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }

    /**
     * 接收信息
     *
     * @param receivedMessage
     * @return
     */
    @PutMapping("/received/message")
    @Anonymous
    public AjaxResult receivedMessage(@RequestBody ReceivedMessage receivedMessage) {
        try {
            String clientNumber = receivedMessage.getFromNumber();
            CustomerChat user = customerChatService.selectChatByClientNumber(clientNumber);
            if (StringUtils.isNull(user)) {
                logger.info("不是目标粉丝发送的消息：" + clientNumber);
                return error("不是目标粉丝发送的消息：" + clientNumber);
            }
            logger.info("接收来自到粉丝的消息：" + clientNumber);
            receivedMessage.setUserType(1);
            receivedMessage.setType("chat");
            webSocketServer.setMessage(receivedMessage.getToNumber(), receivedMessage);
        } catch (Exception e) {
            return error("发送消息失败");
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("code", "101");
        return ajax;
    }

    @Log(title = "客服数据导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerInfo user) {
        List<CustomerInfo> list = cusUserService.selectUserList(user);
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        util.exportExcel(response, list, "whatsapp数据");
    }


    @Log(title = "客服数据导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        List<CustomerInfo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = cusUserService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @Log(title = "客服数据模板", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:changeStatus')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        util.importTemplateExcel(response, "whatsapp数据");
    }


    /**
     * 群名设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:bulk')")
    @Log(title = "群名设置", businessType = BusinessType.UPDATE)
    @PostMapping("/setBulkSend")
    public AjaxResult setBulkSend(@RequestBody BulkSendName bulkSendName) {
        return toAjax(cusUserService.selectToids(bulkSendName));
    }

    /**
     * apiSend设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "apiSend设置", businessType = BusinessType.UPDATE)
    @PostMapping("/apiSend")
    public AjaxResult apiSend(@RequestBody BulkSendName bulkSendName) {
        return toAjax(cusUserService.selectToApi(bulkSendName));
    }


    /**
     * 回访设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "apiSend设置", businessType = BusinessType.UPDATE)
    @PostMapping("/relpyback")
    public AjaxResult relpyback(@RequestBody BulkSendName bulkSendName) {
        int res = statusCheckService.checkGroupCode(bulkSendName.getCallBackTime(),bulkSendName.getGroupCheckData());
        return toAjax(res);
    }


    /**
     * 一键重连
     */
    @PreAuthorize("@ss.hasPermi('customer:user:api')")
    @Log(title = "reconnect", businessType = BusinessType.UPDATE)
    @GetMapping("/reconnect")
    public AjaxResult reconnect() {
        String rspStr = cusUserService.reconnect();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", rspStr);
        return ajax;
    }


    /**
     * TeleName设置
     */
    @PreAuthorize("@ss.hasPermi('customer:user:telegram')")
    @Log(title = "TeleName设置", businessType = BusinessType.UPDATE)
    @PostMapping("/setTelegram")
    public AjaxResult setTelegram(@RequestBody BulkSendName bulkSendName) {
        return toAjax(cusUserService.setTelegram(bulkSendName));
    }


}
